package com.lianjia.analysis.service.impl;

import com.lianjia.analysis.service.CacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Redis缓存服务实现类
 */
@Service("apiCacheService")
public class ApiRedisCacheServiceImpl implements CacheService {

    private static final Logger logger = LoggerFactory.getLogger(ApiRedisCacheServiceImpl.class);
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Override
    public int clearCacheWithPrefix(String prefix) {
        if (prefix == null || prefix.isEmpty()) {
            return 0;
        }
        
        // 使用keys命令查找所有匹配前缀的键
        Set<String> keys = redisTemplate.keys(prefix + "*");
        if (keys == null || keys.isEmpty()) {
            return 0;
        }
        
        int count = keys.size();
        redisTemplate.delete(keys);
        logger.info("已清除{}个缓存，前缀：{}", count, prefix);
        
        return count;
    }

    @Override
    public boolean clearCache(String key) {
        if (key == null || key.isEmpty()) {
            return false;
        }
        
        Boolean result = redisTemplate.delete(key);
        return Boolean.TRUE.equals(result);
    }

    @Override
    public Map<String, Object> getCacheStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取分析相关缓存数量
        int analysisCount = getKeyCountWithPrefix("analysis:");
        stats.put("analysisCount", analysisCount);
        
        // 获取按城市分类的缓存数量
        Map<String, Integer> cityStats = new HashMap<>();
        Set<String> cities = redisTemplate.keys("analysis:city:*");
        if (cities != null) {
            for (String cityKey : cities) {
                String[] parts = cityKey.split(":");
                if (parts.length > 2) {
                    String city = parts[2];
                    cityStats.put(city, cityStats.getOrDefault(city, 0) + 1);
                }
            }
        }
        stats.put("cityStats", cityStats);
        
        // 获取缓存命中率（这里是模拟数据，实际应该通过监控系统获取）
        stats.put("hitRate", 0.85);
        stats.put("missRate", 0.15);
        
        // 获取缓存平均响应时间（毫秒，模拟数据）
        stats.put("avgResponseTime", 5.2);
        
        // 获取总缓存数量
        long totalCount = 0;
        Set<String> allKeys = redisTemplate.keys("*");
        if (allKeys != null) {
            totalCount = allKeys.size();
        }
        stats.put("totalCount", totalCount);
        
        return stats;
    }

    @Override
    public Iterable<String> getAllKeys() {
        Set<String> keys = redisTemplate.keys("*");
        return keys != null ? keys : Collections.emptySet();
    }

    @Override
    public int getKeyCountWithPrefix(String prefix) {
        if (prefix == null || prefix.isEmpty()) {
            return 0;
        }
        
        Set<String> keys = redisTemplate.keys(prefix + "*");
        return keys != null ? keys.size() : 0;
    }
} 